class AuthController {

    def index = {redirect(action:login,params:params) }

    def login = {
        if(User.count()==0){
            render(view:'/createAdmin')
        }else{
            render(view:'/index')
        }
    }

    def createAdmin = {
        def userInstance = new User(params)
        userInstance.role = 'admin'
        session.user = userInstance
        if(!userInstance.hasErrors() && userInstance.save()) {
            flash.message = "User ${userInstance.name} created"
            redirect(controller:'user',action:'show',id:userInstance.id)
        }
        else {
            redirect(action:'login')
        }
    }

    def auth = {
        def userInstance = User.findByNameAndPassword(params.name, params.password)
        if(userInstance){
            session['user'] = userInstance
            redirect(controller:'user',action:'show',id:userInstance.id)
        }else{
            redirect(action:'login')
        }
    }

    def logout = {
        if(session.user){
            session.user = null
        }
        redirect(controller:'auth', action:'login')
    }
}
